package com.example.springboot.controller;

import com.example.springboot.pojo.User;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/register")
    public Map<String, String> register(@RequestBody User user) {
        User u = userService.findUserByUserName(user.getUsername());
        Map<String, String> map = new HashMap<>();
        if (u == null) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            user.setCreatetime(new Timestamp(System.currentTimeMillis()));
            System.out.println(user.getCreatetime());
            int row = userService.insertUserInfo(user);
            System.out.println("插入" + row + "条数据");
            map.put("msg", "注册成功");
            map.put("view", "/page/toLogin");
            return map;
        }
        map.put("msg", "注册失败");
        return map;
    }


    @RequestMapping("/checkLogin")
    public Map<String, String> checkLogin(@RequestBody User user) {
        User u = userService.findUserByUserName(user.getUsername());
        Map<String, String> map = new HashMap<>();
        if (u != null) {
            if (u.getUsername().equals(user.getUsername()) && DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).equals(u.getPassword())) {
                    map.put("msg", "登录成功");
                    map.put("view", "/page/toMenu");
                    userService.updateStatus(u.getId());
                    return map;
            }
            map.put("msg", "用户名或密码错误");

            return map;
        }
        map.put("msg", "没有该用户");

        return map;

    }

    @RequestMapping("/showUserNameOnLine")
    public Map<String, String> userNameOnLine() {
        Map<String, String> map = new HashMap<>();
        map.put("username", userService.findUserIdOnLine().getUsername());
        return map;
    }


}
